/**
 * @program: yygh_parent
 * @ClassName WeiXinController
 * @description:
 * @author: zyw
 * @create: 2023-06-02 10:27
 * @Version 1.0
 **/
package com.atguigu.yygh.user.controller.user;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.common.exception.YyghException;
import com.atguigu.yygh.common.result.R;
import com.atguigu.yygh.common.util.JwtHelper;
import com.atguigu.yygh.model.user.UserInfo;
import com.atguigu.yygh.user.prop.WeiXinConfig;
import com.atguigu.yygh.user.service.UserInfoService;
import com.atguigu.yygh.user.utils.HttpClientUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.util.StringBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/user/userinfo/wx")
public class WeiXinController {

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private WeiXinConfig weiXinConfig;

    @GetMapping("/param")
    @ResponseBody
    public R getWeiXinLoginParam() throws UnsupportedEncodingException {
        String redirectUri = URLEncoder.encode(weiXinConfig.getRedirectUrl(), "UTF-8");
        HashMap<String, Object> map = new HashMap<>();
        map.put("appid", weiXinConfig.getAppId());
        map.put("redirectUri", redirectUri);
        map.put("scope", "snsapi_login");
        map.put("state", System.currentTimeMillis() + "");
        return R.ok().data(map);
    }

    @GetMapping("/callback")
    public String callback(String code, String state) throws Exception {
//        System.out.println("code+state = " + code +":"+ state);
        StringBuilder sb = new StringBuilder();
        sb.append("https://api.weixin.qq.com/sns/oauth2/access_token")
                .append("?appid=%s")
                .append("&secret=%s")
                .append("&code=%s")
                .append("&grant_type=authorization_code");
        String s = String.format(sb.toString(), weiXinConfig.getAppId(), weiXinConfig.getAppSecret(), code);
        String str = HttpClientUtils.get(s);
        System.out.println("str = " + str);
        JSONObject jsonObject = JSONObject.parseObject(str);
        String access_token = jsonObject.getString("access_token");
        String openId = jsonObject.getString("openid");
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("openid", openId);
        UserInfo userInfo = userInfoService.getOne(wrapper);
        if (userInfo == null) {
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append("https://api.weixin.qq.com/sns/userinfo")
                    .append("?access_token=%s")
                    .append("&openid=%s");
            String format = String.format(stringBuilder.toString(), access_token, openId);
            System.out.println("format = " + format);
            String s1 = HttpClientUtils.get(format);
            JSONObject json = JSONObject.parseObject(s1);
            String nickname = json.getString("nickname");
            userInfo = new UserInfo();
            userInfo.setOpenid(openId);
            userInfo.setStatus(1);
            userInfo.setNickName(nickname);
            userInfoService.save(userInfo);
        }
        //验证用户status
        if (userInfo.getStatus() == 0) {
            throw new YyghException(20001, "用户锁定中！");
        }
        HashMap<String, String> map = new HashMap<>();
        //首次登录,根据后端的openid传给前端，在前端判定是否需要手机号绑定
        if (StringUtils.isEmpty(userInfo.getPhone())) {
            map.put("openid", openId);
        } else {
            map.put("openid", "");
        }
        String name = userInfo.getName();
        if (StringUtils.isEmpty(name)) {
            name = userInfo.getNickName();
        }
        map.put("name", name);
        String token = JwtHelper.createToken(userInfo.getId(), name);
        map.put("token", token);
        //跳转到前端页面
        return "redirect:http://localhost:3000/weixin/callback?token="
                +map.get("token")
                + "&openid="
                +map.get("openid")
                +"&name="
                +URLEncoder.encode(map.get("name"),"utf-8");
    }
}
 
